先來學習繪製矩形的方法
strokeRect 使用當前的繪畫樣式,描繪一個起點在 (x, y) 、寬度為 w 、高度為 h 的矩形的方法。
void ctx.strokeRect(x, y, width, height);
再來只要知道滑鼠移動的位置即可知道高寬
const handleDrawCanvas = (point: pointIF) => {
  ...
  case "rectangle":
      const width = point?.x - initialPoint?.x;
      const height = point?.y - initialPoint?.y;
      ctx.strokeRect(initialPoint?.x, initialPoint?.y, width, height);
  break;
  ...
}
 
const handleMouseDown = (event: any) => {
  ...
  case "rectangle":
    initialPoint = { x: point?.x, y: point?.y };
    break;
  ...
};
是不是似曾相似?
還記得,在上一篇我們學習到清空及復原上個畫面完成直線,本篇章利用相同的原理來繪製矩形。
const handleDrawCanvas = (point: pointIF) => {
  ...
  case "rectangle": 
      clearCanvas(); // 補上
      restore(); // 補上
      const width = point?.x - initialPoint?.x;
      const height = point?.y - initialPoint?.y;
      ctx.strokeRect(initialPoint?.x, initialPoint?.y, width, height);
  break;
  ...
}
 
const handleMouseDown = (event: any) => {
  ...
  case "rectangle":
    initialPoint = { x: point?.x, y: point?.y };
    break;
  ...
};
const handleMouseDown = (event: any) => {
  ...
  case "rectangle":
    initialPoint = { x: point?.x, y: point?.y };
    saveCanvas(); // 補上
    break;
  ...
};

完成矩形啦!
順便補充其他矩形的相關參數
ctx.shadowColor = '#d53' // 光暈顏色
ctx.shadowBlur = 20; // 光暈粗度 
這兩者通常會一起使用
先來學習繪製矩形的方法
arcTo 使用給定的控制點和半徑將圓弧添加到當前子路徑。 如果指定參數需要,圓弧會自動使用直線連接到路徑的最新點。
void ctx.arcTo(x1, y1, x2, y2, radius);
給予各個點來繪製帶有圓角的矩形
const handleMouseDown = (event: any) => {
  ...
 case "roundedRectangle":
  clearCanvas();
  restore();
  ctx.strokeStyle = activeColor;
  roundRect(ctx, initialPoint?.x, initialPoint?.y, width, height, 10); // 繪製圓角矩形
  ctx.stroke();
  break;
  ...
};
const roundRect = (ctx ,x ,y ,w ,h , r:圓角的程度) => {
    if (w < 2 * r) r = w / 2;
    if (h < 2 * r) r = h / 2;
    ctx.beginPath();
    ctx.moveTo(x + r, y);
    ctx.arcTo(x + w, y, x + w, y + h, r);
    ctx.arcTo(x + w, y + h, x, y + h, r);
    ctx.arcTo(x, y + h, x, y, r);
    ctx.arcTo(x, y, x + w, y, r);
};
迅速地搞定!
